<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>图片设置</h3>
      <el-form ref="dataForm" :rules="rules" :model="img" label-width="150px">
        <el-form-item label="图片位置" prop="location">
          <el-select v-model="img.location" placeholder="选择图片位置">
            <el-option v-for="(item, index) in locationList" :key="index" :label="item.name" :value="item.id"/>
          </el-select>
          <el-input v-model="img.locaiton" type="hidden" />
        </el-form-item>
        <el-form-item label="图片顺序" prop="order">
          <el-select v-model="img.order" placeholder="选择图片顺序">
            <el-option v-for="(item, index) in orderList" :key="index" :label="item" :value="item"/>
          </el-select>
          <el-input v-model="img.order" type="hidden" />
        </el-form-item>
        <el-form-item label="新闻图片" prop="imageUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeAvatarUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="loading" class="preimg" />
            <div v-show="img.imageUrl" :style="'background-image:url('+img.imageUrl+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="img.imageUrl" type="hidden" />
        </el-form-item>
        <el-form-item label="跳转地址" prop="url">
          <el-input v-model="img.url" placeholder="请输入跳转地址" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="!img.id" type="primary" @click="handleCreate">保存图片</el-button>
      <el-button v-if="img.id" type="primary" @click="handleEdit">更新图片</el-button>
    </div>
  </div>
</template>

<style>
  .el-upload--picture{
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
  }
  .el-upload-list--picture{
    display: none;
  }
  .upload-img .preimg{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
  }
  .el-loading-spinner{
    top:0;
  }
</style>

<script>
import { editImg, createImg, detailImg } from '@/api/imgset'
import { uploadPath, createStorage } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'NewsAdd',
  components: { Editor },
  data() {
    return {
      imgId: '',
      uploadPath,
      img: {
        imageUrl: '', order: 0
      },
      loading: false,
      rules: {
        location: [
          { required: true, message: '请选择图片位置', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '新闻图片不能为空', trigger: 'blur' }
        ]
      },
      locationList: [{ name: '公司Logo', id: 1 }, { name: '企业介绍Banner', id: 2 }, { name: '企业介绍详情', id: 3 }, { name: '新闻Banner', id: 4 }, { name: '二维码', id: 5 }, { name: '一分田轮播图', id: 6 }],
      orderList: [],
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }

    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    const arr = []
    for (let i = 0; i < 100; i++) {
      arr.push(i)
    }
    this.orderList = arr
    this.init()
  },
  methods: {
    init: function() {
      const imgId = this.$route.query.id
      if (imgId) {
        detailImg(imgId).then(response => {
          this.img = Object.assign({}, response.data.data)
          this.img.order = this.imgimg.order ? this.imgimg.order : 0
        })
      }
    },
    handleCancel: function() {
      this.$router.push({ path: '/enterprise/imgslist' })
    },
    handleCreate: function() {
      this.formValidate(1)
    },
    handleEdit: function() {
      this.formValidate(2)
    },
    formValidate: function(type) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalNews = {
            ...this.img
          }
          finalNews.isUse = 0
          if (type === 1) {
            createImg(finalNews)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/enterprise/imgslist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          } else if (type === 2) {
            editImg(finalNews)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/enterprise/imgslist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.img.imageUrl = response.url
        this.loading = false
      }
    },
    handleErrorimgsUrl(response, file, fileList) {
      this.$notify.error({
        title: '失败',
        message: '请重新上传图片'
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.loading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.loading = false
      }
      return isLt2M
    }
  }
}
</script>
